package com.nxy.cpfsfe.busi.bolag;


import com.adtec.starring.datapool.CompSDO;
import com.adtec.starring.datapool.EPOper;
import com.adtec.starring.exception.BaseException;
import com.adtec.starring.struct.dta.DtaInfo;
import com.adtec.starring.util.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nxy.cpfsfe.enumtype.*;
import com.nxy.cpfsfe.mybatis.mapper.TbAMapper;
import com.nxy.cpfsfe.mybatis.mapper.TsPCmdMapper;
import com.nxy.cpfsfe.mybatis.pojo.TbA;
import com.nxy.cpfsfe.mybatis.pojo.TsPCmd;
import com.nxy.cpfsfe.service.CpfsService;
import com.nxy.cpfsfe.util.*;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class NCSNowCreditReceiptBean implements CpfsService {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(NCSNowCreditReceiptBean.class);
	
	SqlSession sqlSession = null;	
	
	/**
	 * 
	 * Description:异步处理
	 *
	 * @author
	 * @data 2019年8月24日
	 */
	@Override
	public void  doService()  {
		// TODO 自动生成的构造函数存根
		
		String tpId = DtaInfo.getInstance().getTpId();
		sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");		
		// 获取输入
		CompSDO inputSdo = (CompSDO) EPOper.getCompSDO(tpId, "ReqBody"); // 获取输入接口
		// 业务报文			
		String bizMsg = (String) inputSdo.getValue("BizMsg")!=null?(String) inputSdo.getValue("BizMsg"):"";
		LOGGER.info("接收到处理NCS贷记回执BizMsg报文数据：[{}]" , bizMsg);
		//解包生成业务map
		Map map = xml2BizMap(bizMsg);
		//云支付前置实时贷记回执NPS.141.001.01报文
		if(!MsgCdOrTpEnum.MSGCD_141.getCode().equals((String)map.get("/transaction/header/msg/msgCd"))){
			LOGGER.warn("NCS贷记回执报文编号应为:[{}]，此报文标识号：[{}]非法",MsgCdOrTpEnum.MSGCD_141.getCode(),map.get("/transaction/header/msg/msgCd"));
			return;
		}
		try {			
			TbA tbA = queryOrgAgSeq(sqlSession, map);
			TsPCmd tsPCmd = queryOrgBizSeq(sqlSession, map);
			if(tbA!=null && tsPCmd!=null){
				map.put("updTm", DateUtil.getTimestamp(new Date()));	
				map.put("orgnBizSta",tbA.getBizSta());
				//更新业务流水交易状态
				sqlSession.getMapper(TsPCmdMapper.class).updateByMap(map);
				//更新账务流水交易状态
				sqlSession.getMapper(TbAMapper.class).updateByMap(map);
				LOGGER.info("账务流水表TbA和支付流水表tsPCmd更新数据成功chlSeqNo:{}",map.get("chlSeqNo"));
				if(!SysEcodeEnum.CPFS.getCode().equals(tbA.getSndSysId())){
					returnCreditReceipt(bizMsg,tbA.getSndSysId());
				}
				//如果交易来源为102实时贷记
				if(MsgCdOrTpEnum.MSGTD_102.getCode().equals(tsPCmd.getMsgTp())){
					//组装501、502

					map.put("/root/MsgHeader/MsgTp",MsgCdOrTpEnum.MSGTD_102.getCode());
					map.put("/root/MsgHeader/CorrId",tsPCmd.getComMsgId());
					map.put("/root/MsgHeader/SndSysId",tsPCmd.getBizSysId());
					map.put("/root/MsgHeader/SndBankId",tsPCmd.getSndBNo());
					JSONObject addInfo = JSON.parseObject(tsPCmd.getAddInfo());
					map.put("NginxUrl",addInfo.get("NginxUrl"));
					map.put("/root/MsgHeader/ClbckUrl",addInfo.get("ClbckUrl"));
					String  nginxResp =   buildNginxResp(map,tsPCmd,MsgCdOrTpEnum.MSGTD_501.getCode());
					String  busResp   =   buildNginxResp(map,tsPCmd,MsgCdOrTpEnum.MSGTD_502.getCode());
					HttpUtil.responseSendJson(nginxResp,busResp,map);
				}

			}else {
				//若没用查到原交易
				LOGGER.error("原交易不存在chlSeqNo:" + map.get("chlSeqNo"));
			}
			
		}catch (Throwable e) {
			LOGGER.error("更新数据失败：业务流水表TbA和支付流水表tsPCmd：xSeqNo或chlSeqNo:["+map.get("xSeqNo")+"]。。。",e);
		}
		
	}

	private String buildNginxResp(Map bizMap, TsPCmd tsPCmd, String msgTp) throws Exception {
		Map<String, String> buildMap = new HashMap<String, String>();
		buildMap.put("RcvSysId", StringUtil.trimObject(bizMap.get("/root/MsgHeader/SndSysId")));
		buildMap.put("SndBankId", tsPCmd.getSndBNo());
		buildMap.put("RcvBankId",  tsPCmd.getRcvBNo());
		buildMap.put("CorrId", tsPCmd.getComMsgId());
		buildMap.put("TrxId",tsPCmd.getXSeqNo());
		buildMap.put("OriTrxId", tsPCmd.getXSeqNo());
		buildMap.put("TrxStsCd",StringUtil.trimObject(bizMap.get("respSta")));
		buildMap.put("BizStsCd", StringUtil.trimObject(bizMap.get("errCd")));
		buildMap.put("BizStsDesc", StringUtil.trimObject(bizMap.get("errDesc")));

		if (MsgCdOrTpEnum.MSGTD_501.getCode().equals(msgTp)) {
			return ResponseUtil.buildGeneral501Xml(buildMap);
		} else {
			return ResponseUtil.buildGeneral502Xml(buildMap);
		}
	}



	//查询账务信息
	private TbA queryOrgAgSeq(SqlSession sqlSession,Map map) {
		TbAMapper tbAMapper = sqlSession.getMapper(TbAMapper.class);
		TbA tbA = new TbA();
		tbA.setCpfsSeqNo((String)map.get("cpfsSeqNo"));
		tbA.setAcqOrgId((String)map.get("acqOrgId"));
		TbA tbAResult = tbAMapper.query(tbA);	
				
		return tbAResult;

	}
	
	//查询支付信息
	private TsPCmd queryOrgBizSeq(SqlSession sqlSession,Map map) {	
		TsPCmdMapper tsPCmdMapper = sqlSession.getMapper(TsPCmdMapper.class);
		TsPCmd tsPCmd = new TsPCmd();	
		tsPCmd.setCpfsSeqNo((String)map.get("cpfsSeqNo"));
		tsPCmd.setAcqOrgId((String)map.get("acqOrgId"));
		TsPCmd tsPCmdResult = tsPCmdMapper.query(tsPCmd);
				
		return tsPCmdResult;

	}
	
	
	
	public static void returnCreditReceipt(String bizMsg, String sndAppCd) {

	     String tpId = DtaInfo.getInstance().getTpId();
	     String msgCd =XmlUtil.getValByXPath(bizMsg,"/transaction/header/msg/msgCd");
		 
		 EPOper.put(tpId, "ReqBean[0].head[0].rcvAppCd", sndAppCd);
    	 EPOper.put(tpId, "ReqBean[0].head[0].reqServCd", msgCd);
	     EPOper.getCompSDO(tpId, "ReqBody").setValue("BizMsg",bizMsg);
	     RpcCommUtil.getInstance().rpcFeToGW(tpId, RpcOutputInfoEnum.OutputName_Pub_Cpfsgw.getCode(),RpcOutputInfoEnum.OutPutSvr_CpfsFwdThrdPrtS.getCode());	  

	     LOGGER.debug("rpc调用GW实时贷记回执报文结束......");
	     
	}
	
	public Map xml2BizMap (String bizMsg){
	    //拆解xml报文为map1
		Map<String, Object> map = null;
		try{
			Map xml2BizMap =XmlUtil.xml2Map(bizMsg);	
			//把map1<String, String>转换成map<String, Object>
			map =xml2BizMap;			
			map = XmlUtil.formatXmlAttr(map,"AddtlInf");
			map.put("cpfsSeqNo",(String)map.get("/transaction/body/FIToFIPmtStsRpt/OrgnlGrpInfAndSts/OrgnlMsgId"));
	
			map.put("xSeqNo",(String)map.get("/transaction/body/FIToFIPmtStsRpt/OrgnlGrpInfAndSts/OrgnlMsgId"));
			map.put("chlSeqNo",(String)map.get("/transaction/body/FIToFIPmtStsRpt/OrgnlGrpInfAndSts/OrgnlMsgId"));
			map.put("respMsgTyp",(String)map.get("/transaction/header/msg/msgCd"));
			map.put("acqOrgId",(String)map.get("/transaction/header/msg/refSndMbrCd"));
			map.put("refMsgCd",(String)map.get("/transaction/header/msg/refMsgCd"));
	
			String bizSts = (String)map.get("/transaction/body/FIToFIPmtStsRpt/OrgnlGrpInfAndSts/StsRsnInf/BizSts");

			//不更新清算日期
			// String clrgD = (String)map.get("/transaction/body/FIToFIPmtStsRpt/OrgnlGrpInfAndSts/StsRsnInf/SttlmDt");
			//map.put("clrgD", clrgD);
			String bizSta =StatEnum.BIZSTA_ING.getCode();
			/*PR00：已清算---PR09：已存款冲销，PR10：已补正
			  PR20：延时成功 ---R00：已清算，PR08：已撤销		  
			*/		
			if("PR00".equals(bizSts)){
				bizSta = StatEnum.BIZSTA_SUC.getCode();//交易成功
			}else if("PR01".equals(bizSts)){
				bizSta = StatEnum.BIZSTA_FAIL.getCode();//交易失败
			}else {
				bizSta = StatEnum.BIZSTA_ING.getCode();//交易处理中
			}
			map.put("bizSta",bizSta);
			map.put("respSta",bizSts);
			map.put("errCd", StringUtil.trimObject(map.get("/transaction/body/FIToFIPmtStsRpt/TxInfAndSts/StsRsnInf/Rsn/Prtry")));
			map.put("errDesc",StringUtil.trimObject(map.get("/transaction/body/FIToFIPmtStsRpt/TxInfAndSts/StsRsnInf/AddtlInf")));
			LOGGER.info("NCSNowCreditReceiptBean更新表参数map：[{}]" , map.toString());
			}catch (Throwable e){
				throw new BaseException(RespCd.NCPO0101,e,MsgCdOrTpEnum.MSGCD_141.getCode()+"报文解包异常");
			}
		return map;
		
	}
	
	
}

